package cn.txy.aop.anno;

import cn.txy.aop.domain.Logs;
import cn.txy.aop.mapper.LogsMapper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;

@Aspect
@Component
public class LogsAspect {

    @Autowired
    private LogsMapper logsMapper;

    // 指定annotation切点表达式，查找@Log注解
    @Around("@annotation(cn.txy.aop.anno.Logs)")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        // 1.开始操作时间
        LocalDateTime now = LocalDateTime.now();
        // 2.设置操作类名
        String className = pjp.getTarget().getClass().getName();
        // 3.操作方法名
        String methodName = pjp.getSignature().getName();
        // 4.方法参数
        Object[] args = pjp.getArgs();
        String methodParams = Arrays.toString(args);
        // 5.执行目标方法以及获取到方法返回值
        long beginTime = System.currentTimeMillis();
        Object result = pjp.proceed();
        long endTime = System.currentTimeMillis();

        // 6.操作耗时
        Long costTime = endTime - beginTime;

        // 获取 HttpServletRequest
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 7.操作Ip
        String ip = request.getRemoteAddr();

        String resultStr = result != null ? result.toString() : "null";

        // 8.记录操作日志，因为没有做登录，所以操作Id和操作用户名称写死
        Logs logs = new Logs(null, 1L, "张三", now,
                className, methodName, methodParams, resultStr, costTime, ip);
        logsMapper.insert(logs);

        return result;
    }

}
